import React, { forwardRef,  useImperativeHandle, useState } from 'react'
import { Image, KeyboardAvoidingView, Modal, Platform, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native'
import { getUUID } from '../utils/UUID';
import { save, load } from '../utils/Storage';
// @ts-ignore
import icon_close_modal from '../assets/icon_close_modal.png';

export default forwardRef((props: any, ref) => {
  const { onLoad } = props

  // 新增还是编辑
  const [isEdit, setIdEdit] = useState(false)

  // 设置id
  const [id, setId] = useState('')

  // 设置账号的类型
  const [type, setType] = useState('游戏')

  const [name, setName] = useState('')

  const [account, setAccount] = useState('');

  const [password, setPassword] = useState('');

  const [visible, setVisible] = useState(false)

  const hide = () => {
    setVisible(false)
  }

  const show = (item:any) => {
    setVisible(true)
    if(item){
      setType(item.type)
      setName(item.name)
      setPassword(item.password)
      setId(item.id)
      setAccount(item.account)
      setIdEdit(true)
    }else{
      setId(getUUID())
      setType('游戏')
      setName('')
      setPassword('')
      setAccount('')
      setIdEdit(false)
    }
    
  }

  // 转发ref中的show hide方法
  useImperativeHandle(ref, () => {
    return {
      show,
      hide,
    }
  });



  // 点击保存
  const onSavePress = () => {
    const newAccount = { id, type, name, account, password }
    console.log('newAccount', newAccount);
    load('accountList').then( (data:any) =>{
      let accountList = data ? JSON.parse(data) : []
      // 如果是编辑 那么移除旧的
      if(isEdit){
        accountList = accountList.filter((item:any) => item.id !== id)
      }
      accountList.push(newAccount)
      save('accountList' ,JSON.stringify(accountList)).then(()=>{
        load('accountList').then((res)=>{
          console.log(res);
        })
        onLoad()
        hide()
      }) 
    })
  }



  const renderTitle = () => {
    return (
      <View style={styles.titleLayout}>
        <Text style={styles.titleTxt}>
          {isEdit ? '修改账号' : '新增账号'}
        </Text>
        <TouchableOpacity
          style={styles.closeButton}
          onPress={hide}
        >
          <Image style={styles.closeImg} source={icon_close_modal}></Image>
        </TouchableOpacity>
      </View>
    )
  }

  const compontendType = (props: any) => {
    const { item, index } = props
    return (<TouchableOpacity
      style={[
        styles.tab,
        index === 0 ? styles.leftTab : index === 3 ? styles.rightTab : {},
        index > 0 && styles.moveLeft1Pix,
        { backgroundColor: type === item ? '#3050ff' : 'transparent' }
      ]}
      key={`${item}`}
      onPress={() => {
        setType(item);
      }}
    >
      <Text style={[
        styles.tabTxt,
        { color: type === item ? 'white' : '#666666' }
      ]}>{item}</Text>
    </TouchableOpacity>)
  }

  const renderType = () => {
    const typesArray = ['游戏', '平台', '银行卡', '其它'];
    return (
      <View style={styles.typesLayout}>
        {
          typesArray.map((item, index) => {
            return (
              compontendType({ item, index })
            )
          })
        }
      </View>
    )
  }

  const renderName = () => {
    return (
      <TextInput
        style={styles.input}
        maxLength={20}
        value={name}
        onChangeText={(value: string) => {
          setName(value || '')
        }}
      />
    )
  }

  const renderAccount = () => {
    return (
      <TextInput
        style={styles.input}
        maxLength={20}
        value={account}
        onChangeText={(value: string) => {
          setAccount(value || '')
        }}
      />
    )
  }

  const renderPassword = () => {
    return (
      <TextInput
        style={styles.input}
        maxLength={20}
        value={password}
        onChangeText={(value: string) => {
          setPassword(value || '')
        }}
      />
    )
  }


  const renderButton = () => {
    return (
      <TouchableOpacity
        style={styles.saveButton}
        onPress={onSavePress}
      >
        <Text style={styles.saveTxt}>保 存</Text>
      </TouchableOpacity>
    )
  }



  return (

    <Modal
      visible={visible}
      // onRequestClose={hide}
      transparent={true}
      statusBarTranslucent={true}
      animationType='fade'
    >
      {/* 这个组件的作用 children 子项永远不会被键盘覆盖 */}
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.container}
      >
        <View style={styles.content}>
          {renderTitle()}
          <Text style={styles.subTitleTxt}>账号类型</Text>
          {renderType()}
          <Text style={styles.subTitleTxt}>账号名称</Text>
          {renderName()}
          <Text style={styles.subTitleTxt}>账号</Text>
          {renderAccount()}
          <Text style={styles.subTitleTxt}>密码</Text>
          {renderPassword()}
          {renderButton()}
        </View>


      </KeyboardAvoidingView>



    </Modal>


  )
})


const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    backgroundColor: '#00000060',
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    width: '80%',
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 12,
  },
  subTitleTxt: {
    fontSize: 12,
    color: '#666666',
    marginTop: 16,
  },
  titleLayout: {
    width: '100%',
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  titleTxt: {
    fontSize: 18,
    color: '#333333',
    fontWeight: '400',
  },
  closeButton: {
    position: 'absolute',
    right: 6,
  },
  closeImg: {
    width: 28,
    height: 28,
    resizeMode: 'contain',
  },
  typesLayout: {
    width: '100%',
    height: 32,
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  tab: {
    flex: 1,
    height: '100%',
    borderWidth: 1,
    borderColor: '#C0C0C0',
    justifyContent: 'center',
    alignItems: 'center',
  },
  leftTab: {
    borderTopLeftRadius: 8,
    borderBottomLeftRadius: 8,
  },
  rightTab: {
    borderTopRightRadius: 8,
    borderBottomRightRadius: 8,
  },
  moveLeft1Pix: {
    marginLeft: -1,
  },
  tabTxt: {
    fontSize: 14,
  },
  input: {
    width: '100%',
    height: 40,
    backgroundColor: '#f0f0f0',
    marginTop: 8,
    borderRadius: 8,
    paddingHorizontal: 12,
    fontSize: 16,
    color: '#333333',
  },
  saveButton: {
    width: '100%',
    height: 44,
    backgroundColor: '#3050ff',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 20,
    borderRadius: 8,
    marginBottom: 6,
  },
  saveTxt: {
    fontSize: 16,
    color: 'white',
    fontWeight: 'bold',
  },
});
